<script lang="ts">
export default {
  name: "AntiqueLine"
};
</script>

<script setup lang="ts">
import { ECharts } from "echarts";
import echarts from "/@/plugins/echarts";
import { onBeforeMount, onMounted, nextTick, watch } from "vue";
import { useEventListener, tryOnUnmounted, useTimeoutFn } from "@vueuse/core";

let echartInstance: ECharts;

const props = defineProps({
  index: {
    type: Number,
    default: 0
  },
  xData: {
    type: Array,
    default: function () {
      return ["open_issues", "forks", "watchers", "star"];
    }
  },
  yData: {
    type: Array,
    default: function () {
      return [3, 204, 1079, 1079];
    }
  }
});

watch(props, value => {
  initechartInstance();
});

function initechartInstance() {
  const echartDom = document.querySelector(".line" + props.index);
  if (!echartDom) return;
  // @ts-ignore
  echartInstance = echarts.init(echartDom);
  //清除旧画布 重新渲染
  echartInstance.clear();
  echartInstance.setOption({
    grid: {
      bottom: "20%",
      height: "68%",
      containLabel: true
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross"
      },
      padding: 8
    },
    xAxis: {
      boundaryGap: true,
      axisTick: {
        show: false
      },
      data: props.xData
    },
    yAxis: {
      axisTick: {
        show: false
      }
    },
    series: [
      {
        data: props.yData,
        itemStyle: {
          color: "#3888fa",
          lineStyle: {
            color: "#3888fa",
            width: 2
          }
        },
        label: {
          show: true,
          position: "top"
        },
        smooth: true,
        type: "line",
        animationDuration: 2800,
        animationEasing: "cubicInOut"
      }
    ]
  });
}

onBeforeMount(() => {
  nextTick(() => {
    initechartInstance();
  });
});

onMounted(() => {
  nextTick(() => {
    useEventListener("resize", () => {
      if (!echartInstance) return;
      useTimeoutFn(() => {
        echartInstance.resize();
      }, 180);
    });
  });
});

tryOnUnmounted(() => {
  if (!echartInstance) return;
  echartInstance.dispose();
  echartInstance = null;
});
</script>

<template>
  <div :class="'line' + props.index" style="width: 100%; height: 70vh"></div>
</template>
